<?php
namespace app\admin\my;

class MyConfig extends My {
    private $_title; // 标题
    private $_suggest; // 副标题
    private $_filter = array(); // 过滤器
    private $_callback = null; // 回调
    private $_data = array(); // 数据
    private $_savePostUrl = array(); // 提交地址
    private $_group = array(); // 分组
    private $_keyList = array(); // 键
    private $_buttonList = array(); // 按钮

    public function title($title) {
        $this->_title = $title;
        $this->meta_title = $title;
        return $this;
    }
    public function suggest($suggest) {
        $this->_suggest = $suggest;
        return $this;
    }
    public function filter($filter) {
        $filter = is_array($filter) ? $filter : explode(',', $filter);
        $this->_filter = $filter;
        return $this;
    }
    public function callback($callback) {
        $this->_callback = $callback;
        return $this;
    }
    public function data($data) {
        $this->_data = $data;
        return $this;
    }
    public function savePostUrl($url) {
        if ( $url ) $this->_savePostUrl = $url;
    }
    public function group($title, $icon, $fields) {
    	$v = array(
    		'title' => $title,
    		'icon' => $icon,
    		'items' => is_array($fields) ? $fields : explode(',', $fields)
    	);
        $this->_group[$title] = $v;
        return $this;
    }
    public function groups($list=array()) {
        foreach ( $list as $key => $v ) {
            $v['items'] = is_array($v['items']) ? $v['items'] : explode(',', $v['items']);
            $this->_group[$key] = $v;
        }
        return $this;
    }
    // -- 键
    public function key($name, $title, $subtitle=null, $type, $inline=10, $opt=null) {
        $this->_keyList[] = array(
        	'name' => $name,
        	'title' => $title,
	        'subtitle' => $subtitle,
	        'type' => $type,
	        'inline' => $inline,
	        'opt' => $opt,
        );
        return $this;
    }
    // -- 隐藏字段 hidden
    public function keyHidden($name, $title, $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'hidden', $inline);
    }
    // -- 密码
    public function keyPassword($name='password', $title='密码', $subtitle=null, $inline=false) {
		return $this->key($name, $title, $subtitle, 'password', $inline);
    }
	// -- 只读文本 readonly
    public function keyReadOnly($name, $title, $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'readonly', $inline);
    }
    // -- 标识
    public function keyId($name='id', $title='标识', $subtitle=null, $inline=false) {
        return $this->keyReadOnly($name, $title, $subtitle, $inline);
    }
	// -- 文本输入 text
    public function keyText($name, $title, $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'text', $inline);
    }
    // -- 标题
    public function keyTitle($name='title', $title='标题', $subtitle=null, $inline=false) {
        return $this->keyText($name, $title, $subtitle, $inline);
    }

    // -- 标签
    public function keyLabel($name, $title, $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'label', $inline);
    }
	// - 图标-------------------chosen-icon
    public function keyIcon($name='icon', $title='图标', $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'icon', $inline);
    }
	// -- 颜色选择器
    public function keyColor($name='color', $title='颜色', $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'colorPicker', $inline);
    }
	// -- 文本域 textarea
    public function keyTextArea($name, $title, $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'textarea', $inline);
    }
	// - 整型 integer
    public function keyInteger($name, $title, $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'integer', $inline);
    }
    // - uid
    public function keyUid($name, $title, $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'uid', $inline);
    }
    // - nestable
    public function keyNestable($name, $title, $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'nestable', $inline);
    }
	// - 单文件上传 file
    public function keyFile($name, $title, $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'file', $inline);
    }
	// - 多文件上传
    public function keyMultiFile($name, $title, $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'multiFile', $inline);
    }
    // - 单图片上传
    public function keyImage($name, $title, $subtitle=null, $inline=false) {
        return $this->key($name, $title, $subtitle, 'image', $inline);
    }
    // - 多图片上传
    public function keyMultiImage($name, $title, $subtitle=null, $inline=false, $limit='') {
        return $this->key($name, $title, $subtitle, 'multiImage', $inline, $limit);
    }
	// - 添加城市选择 - 需安装城市联动插件
    public function keyCity($name=array('province', 'city', 'district'), $title, $subtitle, $inline=false) {
        return $this->key($name, $title, $subtitle, 'city', $inline);
    }
	// - 增加数据时通过列表页选择相应的关联数据ID
    public function keyDataSelect($name, $title, $subtitle=null, $inline=false, $url) {
        $urls = url($url, array('inputid' => $name));
        return $this->key($name, $title, $subtitle, 'dataselect', $inline, $urls);
    }
    // -- 下拉菜单 select
    public function keySelect($name, $title, $subtitle=null, $inline=false, $options) {
        return $this->key($name, $title, $subtitle, 'select', $inline, $options);
    }
    // -- 状态
    public function keyStatus($name='status', $title='状态', $subtitle=null, $inline=false) {
        $map = array(
        	-1 => '删除',
        	0 =>'禁用',
	        1 => '启用',
	        2 => '未审核'
        );
        return $this->keySelect($name, $title, $subtitle, $inline, $map);
    }
    // - 单用户组
    public function keySingleUserGroup($name, $title, $subtitle=null, $inline=false) {
        $options = $this->readUserGroups(); // ---未知
        return $this->keySelect($name, $title, $subtitle, $inline, $options);
    }
    // -- 单选按钮 radio
    public function keyRadio($name, $title, $subtitle=null, $inline=false, $options) {
        return $this->key($name, $title, $subtitle, 'radio', $inline, $options);
    }
    // -- 布尔
    public function keyBool($name, $title, $subtitle=null, $inline=false) {
        $map = array(
        	1 => lang('yes'),
        	0 => lang('no')
        );
        return $this->keyRadio($name, $title, $subtitle, $inline, $map);
    }
    // -- 开关
    public function keySwitch($name, $title, $subtitle=null, $inline=false) {
        $map = array(1 => lang('open'), 0 => lang('close'));
        return $this->keyRadio($name, $title, $subtitle, $inline, $map);
    }
    // -- 多选按钮 checkbox
    public function keyCheckBox($name, $title, $subtitle=null, $inline=false, $options) {
        return $this->key($name, $title, $subtitle, 'checkbox', $inline, $options);
    }
    // - 多用户组
    public function keyMultiUserGroup($name, $title, $subtitle=null, $inline=false) {
        $options = $this->readUserGroups();
        return $this->keyCheckBox($name, $title, $subtitle, $inline, $options);
    }
    // -- 富文本
    public function keyEditor($name, $title, $subtitle=null, $inline=false, $config='', $style=array('width' => '100%', 'height' => '200px')) {
        $toolbars = "toolbars:[[" . $config . "]]";
        if ( empty($config) ) $toolbars = "toolbars:[['source','|','bold','italic','underline','fontsize','forecolor','justifyleft','fontfamily','|','map','emotion','insertimage','insertcode']]";
        if ( $config == 'all' ) $toolbars = 'all';
        $key = array('name' => $name, 'title' => $title, 'subtitle' => $subtitle, 'type' => 'editor', 'config' => $toolbars, 'style' => $style);
        $this->_keyList[] = $key;
        return $this;
    }

	// - 日期选择器 datetime date time
    public function keyTime($name, $title, $subtitle=null, $inline=false, $type='datetime') {
        return $this->key($name, $title, $subtitle, $type, $inline);
    }
    // - 创建时间
    public function keyCreateTime($name='create_time', $title='创建时间', $subtitle=null, $inline=false) {
        return $this->keyTime($name, $title, $subtitle, $inline);
    }
    // - 更新时间
    public function keyUpdateTime($name='update_time', $title='修改时间', $subtitle=null, $inline=false) {
        return $this->keyTime($name, $title, $subtitle, $inline);
    }

    public function button($title, $attr = array()) {
        $this->_buttonList[] = array('title' => $title, 'attr' => $attr);
        return $this;
    }
    // 确定
    public function buttonSubmit($url='', $title='确定') {
        if ( $url=='' ) $url = url(request()->action(), $_GET);
        $this->savePostUrl($url);

        $attr = array();
        $attr['class'] = "btn submit-btn ajax-post btn-success";
        $attr['id'] = 'submit';
        $attr['type'] = 'submit';
        $attr['target-form'] = 'form-horizontal';
        return $this->button($title, $attr);
    }
	// 返回
    public function buttonBack($title='返回') {
        $attr = array();
        $attr['onclick'] = 'javascript: history.back(-1); return false;';
        $attr['class'] = 'btn btn-return';
        return $this->button($title, $attr);
    }
    // 按钮-链接
    public function buttonLink($title='按钮', $attr) {
        $attr['onclick'] = 'javascript: location.href=\'' . $attr['href'] . '\'; return false;';
        return $this->button($title, $attr);
    }


    public function fetch($template='', $vars=array(), $replace=array(), $config=array()) {
        foreach ( $this->_keyList as &$e ) {
            if ( $e['type'] == 'multiInput' ) $e['name'] = explode('|', $e['name']);

            if ( is_array($e['name']) ) {
                $i = 0;
                $n = count($e['name']);
                while ( $n > 0 ) {
                    $e['value'][$i] = $this->_data[$e['name'][$i]];
                    $i++;
                    $n--;
                }
            } else {
            	if ( isset($this->_data[$e['name']]) ) {
					$e['value'] = $this->_data[$e['name']];
            	} else {
                	$e['value'] = '';
            	}
            }
        }

        // 编译按钮的html属性
        foreach ( $this->_buttonList as &$button ) {
            $button['attr'] = $this->compileHtmlAttr($button['attr']);
        }

        $this->assign('groups', $this->_group);
        $this->assign('title', $this->_title);
        $this->assign('suggest', $this->_suggest);
        $this->assign('keyList', $this->_keyList);
        $this->assign('buttonList', $this->_buttonList);
        $this->assign('savePostUrl', $this->_savePostUrl);

        return parent::fetch('config');
    }
	// 多选菜单
    public function keyChosen($name, $title, $subtitle=null, $options) {
        if ( key($options) === 0 ) {
            if ( !is_array(reset($options)) ) {
                foreach ( $options as $key => &$val ) {
                    $val = array($val, $val);
                }
                unset($key, $val);
            }
        } else {
            foreach ( $options as $key => &$val ) {
                foreach ( $val as $k => &$v ) {
                    if ( !is_array($v) ) $v = array($v, $v);
                }
                unset($k, $v);
            }
            unset($key, $val);
        }
        return $this->key($name, $title, $subtitle, 'chosen', $options);
    }
	// keyMultiInput 输入组组件
    public function keyMultiInput($name, $title, $subtitle, $config, $style=null) {
        empty($style) && $style = 'width: 400px;';
        $key = array(
        	'name' => $name,
        	'title' => $title,
	        'subtitle' => $subtitle,
	        'type' => 'multiInput',
	        'config' => $config,
	        'style' => $style
        );
        $this->_keyList[] = $key;
        return $this;
    }
	// 自动处理配置存储事件，配置项必须全大写
    public function handleConfig() {
        if ( IS_POST ) {
            $success = false;
            $configModel = D('Config');

            foreach ( I('') as $k => $v) {
                if ( in_array($k, $this->_filter) ) {
                    $success = 1;
                    continue;
                }
                $config['name'] = '_' . strtoupper(CONTROLLER_NAME) . '_' . strtoupper($k);
                $config['type'] = 0;
                $config['title'] = '';
                $config['group'] = 0;
                $config['extra'] = '';
                $config['remark'] = '';
                $config['create_time'] = time();
                $config['update_time'] = time();
                $config['status'] = 1;
                $config['value'] = is_array($v) ? implode(',', $v) : $v;
                $config['sort'] = 0;
                if ( $configModel->add($config, null, true) ) $success = 1;
                $tag = 'conf_' . strtoupper(CONTROLLER_NAME) . '_' . strtoupper($k);
                S($tag, null);
            }
            if ( $success ) {
                if ( $this->_callback ) {
                    $str = $this->_callback;
                    A(CONTROLLER_NAME)->$str(I(''));
                }
                header('Content-type: application/json');
                exit(json_encode(array('info' => lang('_SUCCESS_CONF_SAVE_') . lang('_PERIOD_'), 'status' => 1, 'url' => __SELF__)));
            } else {
                header('Content-type: application/json');
                exit(json_encode(array('info' => lang('_FAIL_CONF_SAVE_') . lang('_PERIOD_'), 'status' => 0, 'url' => __SELF__)));
            }
        } else {
            $configs = D('Config')->where(array('name' => array('like', '_' . strtoupper(CONTROLLER_NAME) . '_' . '%')))->limit(999)->select();
            $data = array();
            foreach ( $configs as $k => $v ) {
                $key = str_replace('_' . strtoupper(CONTROLLER_NAME) . '_', '', strtoupper($v['name']));
                $data[$key] = $v['value'];
            }
            return $data;
        }
    }

    private function readUserGroups() {
        $list = model('AuthGroup')->where(array('status' => 1))->order('id asc')->select();
        $result = array();
        foreach ( $list as $group ) {
            $result[$group['id']] = $group['title'];
        }
        return $result;
    }
	// 解析看板数组
    public function parseNestableArray($data, $item=array(), $default=array()) {
        if ( empty($data) ) {
            $head = reset($default);
            if ( !array_key_exists("items", $head) ) {
                $temp = array();
                foreach ( $default as $k => $v ) {
                    $temp[] = array('data-id' => $k, 'title' => $k, 'items' => $v);
                }
                $default = $temp;
            }
            $result = $default;
        } else {
            $data = json_decode($data, true);
            $item_d = getSubByKey($item, 'data-id');
            $all = array();
            foreach ( $data as $key => $v ) {
                $data_id = getSubByKey($v['items'], 'data-id');
                $data_d[$key] = $v;
                unset($data_d[$key]['items']);
                $data_d[$key]['items'] = $data_id ? $data_id : array();
                $all = array_merge($all, $data_id);
            }
            unset($v);
            foreach ( $item_d as $val ) {
                if ( !in_array($val, $all) ) $data_d[0]['items'][] = $val;
            }
            unset($val);
            foreach ( $all as $v ) {
                if ( !in_array($v, $item_d) ) {
                    foreach ( $data_d as $key => $val ) {
                        $key_search = array_search($v, $val['items']);
                        if ( !is_bool($key_search) ) unset($data_d[$key]['items'][$key_search]);
                    }
                    unset($val);
                }
            }
            unset($v);
            $item_t = array();
            foreach ( $item as $val ) {
                $item_t[$val['data-id']] = $val['title'];
            }
            unset($v);
            foreach ( $data_d as &$v ) {
                foreach ( $v['items'] as &$val ) {
                    $t = $val;
                    $val = array();
                    $val['data-id'] = $t;
                    $val['title'] = $item_t[$t];
                }
                unset($val);
            }
            unset($v);

            $result = $data_d;
        }

        return $result;
    }

    public function setDefault($data, $key, $value) {
        $data[$key] = $data[$key]!=null ? $data[$key] : $value;
        return $data;
    }
    public function keyDefault($key, $value) {
        $data = $this->_data;
        $data[$key] = $data[$key]!==null ? $data[$key] : $value;
        $this->_data = $data;
        return $this;
    }
    public function groupLocalComment($group_name, $mod) {
        $mod = strtoupper($mod);
        $this->keyDefault($mod . '_LOCAL_COMMENT_CAN_GUEST', 1);
        $this->keyDefault($mod . '_LOCAL_COMMENT_ORDER', 0);
        $this->keyDefault($mod . '_LOCAL_COMMENT_COUNT', 10);
        $this->keyRadio($mod . '_LOCAL_COMMENT_CAN_GUEST', lang('_COMMENTS_ALLOW_VISITOR_IF_'), lang('_ALLOW_DEFAULT_'), array(0 => lang('_DISALLOW_'), 1 => lang('_ALLOW_')))
            ->keyRadio($mod . '_LOCAL_COMMENT_ORDER', lang('_COMMENTS_SORT_'), lang('_DESC_DEFAULT_'), array(0 => lang('_DESC_'), 1 => lang('_ASC_')))
            ->keyText($mod . '_LOCAL_COMMENT_COUNT', lang('_COMMENTS_PAGE_DISPLAY_COUNT_'), lang('_COMMENTS_PAGE_DISPLAY_COUNT_DESC'));
        $this->group($group_name, $mod . '_LOCAL_COMMENT_CAN_GUEST,' . $mod . '_LOCAL_COMMENT_ORDER,' . $mod . '_LOCAL_COMMENT_COUNT');
        return $this;
    }

    public function keyUserDefined($name, $title, $subtitle, $display='', $param='') {
        $this->assign('param', $param);
        $this->assign('name', $name);
        $html = $this->fetch($display);

        $key = array(
        	'name' => $name,
        	'title' => $title,
	        'subtitle' => $subtitle,
	        'type' => 'userDefined',
	        'definedHtml' => $html
        );
        $this->_keyList[] = $key;
        return $this;
    }

    public function addCustomJs($script) {
        $this->assign('myJs', $script);
    }
}